using Microsoft.Practices.Unity;
using UnityDemo.InstanceManagerCode.LifeTimeModels;
using UnityDemo.Models;

namespace UnityDemo.InstanceManagerCode.LifetimeTypes
{
    internal class ExternallyControlledLifetimeManagerSample : ISample
    {
        //3.ExternallyControled            http://msdn.microsoft.com/en-us/library/microsoft.practices.unity.externallycontrolledlifetimemanager.aspx

        //ExternallyControlledLifetimeManager. This lifetime manager allows you to register type mappings and existing
        //objects with the container so that it maintains only a weak reference to the objects it creates when you call
        //the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes based
        //on attributes or constructor parameters within that class. Unity returns the same instance of the registered
        //type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects
        //instances into other classes. However, the container does not hold onto a strong reference to the object after
        //it creates it, which means that the garbage collector can dispose of the object if no other code is holding a
        //strong reference to it.
        public ExternallyControlledLifetimeManagerSample()
        {
            var container = new UnityContainer();

            container.RegisterType<SingletonInstance>(new ContainerControlledLifetimeManager());
            container.RegisterType<PerInstance>();
            container.RegisterType<ExternalInstanceLifetime>(new ExternallyControlledLifetimeManager());
            container.RegisterType<PerThredInstance>(new PerThreadLifetimeManager());
            container.RegisterType<HierarchicalLifetimeInstance>(new HierarchicalLifetimeManager());

            var externalInstance1 = container.Resolve<ExternalInstanceLifetime>();
            externalInstance1.PrintHashCode();

            var externalInstance2 = container.Resolve<ExternalInstanceLifetime>();
            externalInstance2.PrintHashCode();
        }
    }
}